package com.xhxi.photobooker.controller;

import com.xhxi.photobooker.entity.Order;
import com.xhxi.photobooker.entity.Photographer;
import com.xhxi.photobooker.entity.User;
import com.xhxi.photobooker.result.Result;
import com.xhxi.photobooker.service.OrderService;
import com.xhxi.photobooker.service.PhotographerService;
import com.xhxi.photobooker.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/orders")
public class OrderController {

    @Autowired
    private UserService userService;
    @Resource
    private OrderService orderService;
    @Autowired
    private PhotographerService photographerService;

    @PostMapping("/user/create")
    public Result<Order> createOrder(@RequestBody Order order) {
        Order created = orderService.createOrder(order);
        return Result.success(created);
    }

    @GetMapping("/user/{userId}")
    public Result<List<Order>> listUserOrders(@PathVariable Long userId) {
        List<Order> orders = orderService.listUserOrders(userId);
        return Result.success(orders);
    }

    @PutMapping("/{id}/cancel")
    public Result<Order> cancelOrder(@PathVariable Long id, @RequestParam Long userId) {
        Order order = orderService.cancelOrder(id, userId);
        return Result.success(order);
    }

    @PostMapping("/{orderId}/chat")
    public ResponseEntity<String> startChat(
            @PathVariable Long orderId,
            Principal principal,
            HttpServletRequest request
    ) {
        // 1. 获取订单信息
        Order order = orderService.selectByOrderId(orderId);
        if (order == null) {
            return ResponseEntity.badRequest().body("订单不存在");
        }

        // 2. 验证身份（当前用户是否是订单相关方）
        Long userId = Long.parseLong(principal.getName());
        if (!userId.equals(order.getUserId()) && !userId.equals(order.getPhotographerId())) {
            return ResponseEntity.status(403).body("无权限");
        }

        // 3. 返回 WebSocket 连接地址
        String userKey = "user:" + userId;
        String photographerKey = "photographer:" + order.getPhotographerId();

        return ResponseEntity.ok("ws://" + request.getServerName() + ":" + request.getServerPort()
                + "/ws/chat/user/" + userId + "?orderId=" + orderId);
    }

    @GetMapping("/{id}")
    public Result<Map<String, Object>> getOrderDetail(@PathVariable Long id) {
        Order order = orderService.selectByOrderId(id);
        if (order == null) {
            return Result.error("订单不存在");
        }
        Photographer photographer = photographerService.findPhotographerById(order.getPhotographerId());
        User user = userService.findUserById(order.getUserId());
        Map<String, Object> result = new HashMap<>();
        result.put("order", order);
        result.put("photographer", photographer);
        result.put("user", user);
        return Result.success(result);
    }

    @PutMapping("/{id}/complete")
    public Result<Boolean> completeOrder(@PathVariable Long id) {
        try {
            boolean result = orderService.finishOrder(id);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("完成订单失败: " + e.getMessage());
        }
    }

    @GetMapping("/list")
    public Result<List<Order>> getAllOrders() {
        try {
            List<Order> orders = orderService.getAllOrders();
            return getListResult(orders);
        } catch (Exception e) {
            return Result.error("获取订单列表失败: " + e.getMessage());
        }
    }

   //仪表盘订单数据（近5条订单数据）
   @GetMapping("/recent")
    public Result<List<Order>> getRecentOrders(@RequestParam(defaultValue = "5") int limit){
       List<Order> orders = orderService.getRecentOrders(limit);
       return getListResult(orders);
   }

    private Result<List<Order>> getListResult(List<Order> orders) {
        for (Order order : orders) {
            // 查用户
            User user = userService.findUserById(order.getUserId());
            order.setUserName(user != null ? user.getUsername() : "-");
            // 查摄影师
            Photographer photographer = photographerService.findPhotographerById(order.getPhotographerId());
            order.setPhotographerName(photographer != null ? photographer.getName() : "-");
        }

        return Result.success(orders);
    }

}